package com.zjj.lbw.spring6.config;

import com.zjj.lbw.spring6.filter.ZjjBootServletFilter;
import com.zjj.lbw.spring6.filter.ZjjLoginFilter;
import com.zjj.lbw.spring6.mapper.UserMapper;
import com.zjj.lbw.spring6.service.ZjjUserService;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

//@Configuration
class SpringSecurityConfiguration {
    @Autowired
    private AuthenticationManagerBuilder authenticationManagerBuilder;

    @Autowired
    private ZjjUserService zjjUserService;

//    @Bean
//    public UserDetailsService inMemoryUserDetailsManager(SecurityProperties properties,
//                                                         ObjectProvider<PasswordEncoder> passwordEncoder) {
//        SecurityProperties.User user = properties.getUser();
//        List<String> roles = user.getRoles();
//        return new InMemoryUserDetailsManager(
//                User.withUsername("zjj")
//                        .password("{noop}123")
//                        .roles(StringUtils.toStringArray(roles))
//                        .build());
//    }

    @Bean
    public FilterRegistrationBean registrationBean() {
        FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new ZjjBootServletFilter());
        filterFilterRegistrationBean.setUrlPatterns(List.of("/*"));
        return filterFilterRegistrationBean;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(request -> {
            request.requestMatchers("/private").authenticated()
                    .anyRequest().permitAll();
        });
        httpSecurity
//                .formLogin(form -> form
//                                .loginPage("/zjjLogin")
//                                .loginProcessingUrl("/doLogin")
////                        .defaultSuccessUrl("/index", true)
////                        .failureUrl("/fail")
//                                .successHandler(new AuthenticationSuccessHandler() {
//
//                                    @Override
//                                    public void onAuthenticationSuccess(HttpServletRequest request,
//                                                                        HttpServletResponse response,
//                                                                        Authentication authentication)
//                                            throws IOException, ServletException {
//                                        response.getWriter().write("login success");
//                                    }
//                                })
//                                .failureHandler(new AuthenticationFailureHandler() {
//
//                                    @Override
//                                    public void onAuthenticationFailure(HttpServletRequest request,
//                                                                        HttpServletResponse response,
//                                                                        AuthenticationException exception)
//                                            throws IOException, ServletException {
//                                        response.getWriter().write("login fail");
//                                    }
//                                })
//                )
                .addFilterAt(new ZjjLoginFilter(authenticationManagerBuilder.getOrBuild()), UsernamePasswordAuthenticationFilter.class)
//                .userDetailsService(zjjUserService)
                .csrf(AbstractHttpConfigurer::disable);
        return httpSecurity.build();
    }
}
